package com.lingyi.common.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.lingyi.common.constant.HttpStatus;
import com.lingyi.common.core.domain.BasePlusEntity;
import com.lingyi.common.enums.DeleteStatus;
import com.lingyi.common.exception.ServiceException;
import com.lingyi.common.utils.DateUtils;
import com.lingyi.common.utils.SecurityUtils;
import com.lingyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    static final Logger logger = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (ObjectUtils.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BasePlusEntity) {
                BasePlusEntity basePlusEntity = (BasePlusEntity) metaObject.getOriginalObject();
                Date createTime = ObjectUtil.isNotNull(basePlusEntity.getCreateTime()) ? basePlusEntity.getCreateTime() : DateUtils.getNowDate();
                basePlusEntity.setCreateTime(createTime);
                basePlusEntity.setDelFlag(DeleteStatus.NO.getCode());
            }

        } catch (Exception e) {
            logger.error("自动注入异常:{}", e.getMessage());
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.UNAUTHORIZED);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (ObjectUtils.isNotEmpty(metaObject) && metaObject.getOriginalObject() instanceof BasePlusEntity) {
                BasePlusEntity basePlusEntity = (BasePlusEntity) metaObject.getOriginalObject();
                Date modifyTime = ObjectUtils.isNotEmpty(basePlusEntity.getUpdateTime()) ? basePlusEntity.getUpdateTime() : DateUtils.getNowDate();
                basePlusEntity.setUpdateTime(modifyTime);
                if (StringUtils.isNotEmpty(SecurityUtils.getUsername())) {
                    basePlusEntity.setUpdateBy(SecurityUtils.getUsername());
                }
            }
        } catch (Exception e) {
            logger.error("自动注入异常:{}", e.getMessage());
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.UNAUTHORIZED);
        }
    }
}
